import { InnerMineEntity } from "GameLoop/WorldState/EntityManager/Entitys";
import { State } from "framework/FSM/AState";
import { ActionArgHelper } from "../../../ActionManager/ActionArgHelper";




/**
 * 采集行为
 */ 
 /*@profile*/
export class Harvester<T extends IStateArg<Creep>>  extends State<T>
{
    /**
     * 采集工行为
     * @param arg 
     */
    public  getActions(arg:T):Action[]
    {
        // 1.找到自己的bind的实体
        // 2.
        
        const creep = arg.entity;
        if(!creep.memory.bindid)
        {

            return []
        }
 
        const bindMine = arg.entity.getEntityByID<InnerMineEntity>(creep.memory.bindid);
        if(!bindMine.getNodeMemory().sites || bindMine.getNodeMemory().sites?.length ==0)
        {
            // 没有site
            const sites = bindMine.getSource().pos.lookForInRange(LOOK_CONSTRUCTION_SITES,3);
            if(sites)
            {
                bindMine.getNodeMemory().sites = sites.map(e=>e.constructionSite.id);
            }
        }
        const memorysites = bindMine.getNodeMemory().sites;
        if(creep.store.getUsedCapacity()==0)
        {
            creep.memory.state = 0;

        }
        else  if(creep.store.getFreeCapacity()==0)
        {
            if(memorysites?.length || bindMine.getNodeMemory().containerId)
            {
                creep.memory.state = 1;
            }
        }
        if( creep.memory.state )
        {
            // 工作 建设。或者修理.或者transfer
            if(memorysites)
            {
                for(let i =0;i<memorysites.length;)
                {
                    const site = Game.getObjectById(memorysites[i]);
                    if(!site)
                    {
                        memorysites.splice(i,1);
                    }
                    else
                    {
                        return [ActionArgHelper.actionBuild(creep,site)]
                    }
                }
            }

            // 有需要修理的
            const containerid = bindMine.getNodeMemory().containerId;
            if(containerid)
            {
                const container = Game.getObjectById(containerid);
                if(container && container.hits<container.hitsMax*0.8)
                {
                    return [ActionArgHelper.actionRepair(creep,container)]
                }
            }
        }
        else
        {
            // 采集
            return [ActionArgHelper.actionHarvest(creep,bindMine.getSource())]
        }
        return [ ];
    }
}
